package service

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/plugin/cusservice/model"
	"encoding/base64"
	"errors"
	"gorm.io/gorm"
	"time"
)

type CustomerServiceService struct{}

func (e *CustomerServiceService) CreateMsg(kfInfo model.SysService, userInfo model.SysTestUser, msgType int64, content string, isKf string) (err error) {
	msgRecord := &model.SysServiceRecord{
		ServiceId:   kfInfo.Id,
		Uid:         userInfo.Id,
		Message:     base64.StdEncoding.EncodeToString([]byte(content)),
		MessageType: msgType,
		UpdateTime:  time.Now().Unix(),
		Avatar:      userInfo.Avatar,
		Nickname:    userInfo.Nickname,
		Online:      1,
	}
	var record model.SysServiceRecord

	eErr := global.GVA_DB.Where("service_id = ?", kfInfo.Id).Where("uid = ?", userInfo.Id).First(&record).Error
	if errors.Is(eErr, gorm.ErrRecordNotFound) {
		msgRecord.AddTime = time.Now().Unix()
		global.GVA_DB.Create(msgRecord)
	} else {
		global.GVA_DB.Model(&model.SysServiceRecord{}).Where("id = ?", record.Id).Updates(msgRecord)
	}

	//插入消息记录
	msg := map[string]interface{}{
		"service_id": kfInfo.Id,
		"uid":        userInfo.Id,
		"content":    base64.StdEncoding.EncodeToString([]byte(content)),
		"msg_type":   msgType,
		"is_view":    0,
		"add_time":   time.Now().Unix(),
		"is_kf":      isKf,
	}
	err = global.GVA_DB.Model(&model.SysServiceMsg{}).Create(msg).Error
	return err
}
